
package com.bogo.dbtable.modelVo.result;



import com.bogo.dbtable.tool.enums.ResultCode;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;


import java.io.Serializable;


/**
 * @author ZKzha
 * @date 2019-08-13 13:53
 */
public class ApiResult implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private String resultName;

    private String result;

    private String msg;

    private Integer code;

    public ApiResult() {

    }

    public ApiResult(Integer code) {
        this.code = code;
    }

    public ApiResult(Integer code, String message) {
        this.code = code;
        this.setMsg(message);
    }

    public String getResult() {
        return result;
    }

    public void setResult(Object o) throws JsonProcessingException {
        ObjectMapper om = new ObjectMapper();
        //现在需要在中间加一个 用于将LocalDatetime 转为string
        om.registerModule(new JavaTimeModule());
        this.result = om.writeValueAsString(o);
        this.resultName = o.getClass().getName();
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public static ApiResult success() {
        ApiResult result = new ApiResult();
        result.setResultCode(ResultCode.SUCCESS);
        return result;
    }

    public static ApiResult success(Object data) {
        ApiResult result = new ApiResult();
        result.setResultCode(ResultCode.SUCCESS);
        try {
            result.setResult(data);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static ApiResult failure(ResultCode resultCode) {
        ApiResult result = new ApiResult();
        result.setResultCode(resultCode);
        return result;
    }

    public static ApiResult failure(ResultCode resultCode, Object data) {
        ApiResult result = new ApiResult();
        result.setResultCode(resultCode);
        try {
            result.setResult(data);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return result;
    }

    public void setResultCode(ResultCode code) {
        this.setCode(code.code());
        this.setMsg(code.message());
    }


}
